package com.example.shushiyunsst.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.ViewFlipper
import androidx.annotation.DimenRes
import com.example.shushiyunsst.R

/*
    公告组件封装
 */
class NewsFlipperView
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    FrameLayout(context, attrs, defStyleAttr) {

    private val mFlipperView: ViewFlipper

    private var itemLayoutId= R.layout.layout_news_flipper

    private var flipperViewId= R.id.mFlipperView

    private var moreOverClickListener: SubClassifyMoreOverClickListener?=null

    fun setMreOverClickListener(moreOverClickListener: SubClassifyMoreOverClickListener?){
        this.moreOverClickListener=moreOverClickListener
    }

    init {
        val array = context.obtainStyledAttributes(attrs, R.styleable.NewsFlipperView)
        itemLayoutId=array.getResourceId(R.styleable.NewsFlipperView_flipper_item_layout,itemLayoutId)
        flipperViewId=array.getResourceId(R.styleable.NewsFlipperView_flipper_item_flipperViewId,flipperViewId)
        array.recycle()

        val rootView = View.inflate(context, itemLayoutId, null)
        mFlipperView = rootView.findViewById(flipperViewId)
        mFlipperView.setInAnimation(context, R.anim.news_bottom_in)
        mFlipperView.setOutAnimation(context, R.anim.news_bottom_out)

        addView(rootView)

        findViewById<View>(R.id.subClassifyMoreOver)?.setOnClickListener {
            moreOverClickListener?.clickListener()
        }
    }

    public interface SubClassifyMoreOverClickListener{
        fun clickListener()
    }


    /*
        构建公告
     */
    private fun buildNewsView(text: String): View {

        val inflate = View.inflate(context, R.layout.news_flipper_view_item, null)

        val textTv:TextView=  inflate.findViewById(R.id.textTv)

        textTv.text = text

        return inflate
    }

    fun dimen(@DimenRes dimen: Int):Int{
        return context.resources.getDimensionPixelSize(dimen)
    }

    fun px2sp(px: Int):Float{
        return  px.toFloat() / context.resources.displayMetrics.scaledDensity
    }

    /*
        设置公告数据
     */
    fun setData(data: Collection<String>) {
        mFlipperView.removeAllViews()
        for (text in data) {
            mFlipperView.addView(buildNewsView(text))
        }
//        start()
        mFlipperView.startFlipping()

//        mFlipperView.stopFlipping()
    }

    fun start(){
        mFlipperView.startFlipping()
    }

    fun stop(){
        mFlipperView.stopFlipping()
    }
}